import datastructure.linklist.ListNode;

/**
 * @Author ZhangCuirong
 * @Date 2025/8/12 9:17
 * @description:
 */
public class Solution19 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head.next == null && n == 1) {
            return head;
        }
        ListNode dummy = new ListNode(-1, head);
        ListNode p1 = dummy;
        ListNode p2 = dummy;
        for (int i = 0; i < n; i++) {
            if (p1 != null) {
                p1 = p1.next;
            }
        }
        while (p1 != null && p1.next != null) {
            p1 = p1.next;
            p2 = p2.next;
        }
        p2.next = p2.next.next;
        return dummy.next;
    }

    public static void main(String[] args) {
        Solution19 solution = new Solution19();
        ListNode head = ListNode.arrayToList(new int[]{1, 2, 3, 4});
        ListNode newHead = solution.removeNthFromEnd(head, 4);
        ListNode.printListWithCycleCheck(newHead);
    }
}
